// dropdown组件的另一种实现方式，使用rendervnode的实现方式(只用ts不用vue)，vnode节点不再需要做单独处理，可以直接渲染
import { computed, defineComponent,Fragment,ref} from 'vue';
import type {PropType } from 'vue'
import type { Placement,Options } from '@popperjs/core';
import type { MenuOptions } from './types';
import Tooltip from '../Tooltip/TooltipMain.vue'
import type { TooltipInstance } from '../Tooltip/types';
export default defineComponent ({
  name:'VkDropdown',
  props: {
    placement:{
      type: String as PropType<Placement>, 
      default: 'bottom'
    },
    trigger:{
      type:String as PropType<'hover'|'click'>,
      default: 'hover'
    },
    transition: {
      type: String, default: 'fade'
    },
    openDelay:{
      type: Number, 
      default: 0
    },
    closeDelay: {
      type:Number, 
      default: 0,
    },
    popperOptions:{
      type:Object as PropType<Options>,
    },
    menuOptions:{
      type: Array as PropType<MenuOptions[]>, 
      required: true,
    },
    closeAfterClick:{
      type: Boolean, 
      default: true
    }
  },
  emits:['visible-change','select'],
  setup(props, { slots, emit,expose}) {
    const tooltipRef = ref<TooltipInstance | null>(null);
    const itemClick=(e:MenuOptions)=>{
       if(e.disabled) {
        return
       }
       emit('select',e)
      if(props.closeAfterClick) {
        tooltipRef.value?.hide()
      }

    }
    const visibleChange=(e:boolean)=>{
      emit('visible-change',e)
    }
    const options=computed(()=>{
      return props.menuOptions.map(item=>{
          return (
            <Fragment key={item.key}>
               {item.divided?<li role="separator" class="divided-placeholder"/> :''}
               <li 
                // 静态class直接设置为true
                 class={{'vk-dropdown__item':true,'is-disabled':item.disabled,'is-divided':item.divided}}
                 id ={`dropdown-item-${item.key}`}
                 onClick={()=>itemClick(item)}
               >
                  {item.label}
               </li>
            </Fragment>
          )
      })
    })
    expose({
      show:()=>tooltipRef.value?.show(),
      hide:()=>tooltipRef.value?.hide(),
    })
    return ()=>(
     <div
       class="vk-dropdown"
     >
      <Tooltip
        placement={props.placement}
        trigger={props.trigger}
        popperOptions={props.popperOptions}
        openDelay={props.openDelay}
        closeDelay={props.closeDelay}
        ref={tooltipRef}
        onVisible-change={visibleChange}
      >

        {{
          // 默认插槽，触发区 
          default:()=>slots.default&&slots.default(),
          // 具名插槽，菜单展示区
          content:()=>(
            <ul class="vk-dropdown__menu">
                {options.value}
            </ul>
          )
        }}
      </Tooltip>

     </div>
    )
  },

})
